package com.lyeducation.controllers.system;

import com.lyeducation.util.controllerUtil.JsonConstans;
import com.lyeducation.util.controllerUtil.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import weixin.popular.api.SnsAPI;
import weixin.popular.bean.sns.SnsToken;
import weixin.popular.bean.user.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 微信其他功能开发
 */
@RestController
@RequestMapping("/login")
public class WxDevController {

    //    @Autowired
//    private TokenUtil tokenUtil;
//    @Autowired
//    private WxService wxUserService;
    @Autowired
    private Wx wx;

//    @Value("${wx.appId}")
//    private String appID;//这里是AppId,我放到配置文件中了,也可以在这里写,直接定义全局变量,下面的开发者密码一样
//    @Value("${wx.appSecret}")
//    private String appSecret;//AppSecret,开发者密码

    /**
     * 网页微信授权登录接口
     *
     * @return
     */
    @RequestMapping(value = "/wechat")
    public void wxLogin(String url, HttpServletResponse response) throws Exception {
        System.out.println("授权登录url:" + url);
        String urls = SnsAPI.connectOauth2Authorize(wx.getAppId(), url, true, "STATE");
        response.sendRedirect(urls);
    }

    @RequestMapping(value = "/goIndex")
    public JsonResult goToIndex(HttpServletRequest request) throws IOException {
        String code = request.getParameter("code");
        if (code == null || "".equals(code)) {
            return JsonResult.putFail(JsonConstans.ERR_CODE_NOTEXISTS.toString());
        }

        SnsToken snsToken = SnsAPI.oauth2AccessToken(wx.getAppId(), wx.getAppSecret(), code);
        String errcode = snsToken.getErrcode();
        if (errcode != null && !"".equals(errcode)) {
            return JsonResult.putFail("微信获取出错");
        }
        User user = SnsAPI.userinfo(snsToken.getAccess_token(), snsToken.getOpenid(), "zh_CN", 1);
        String errcode1 = user.getErrcode();
        if (errcode1 != null && !"".equals(errcode1)) {
            return JsonResult.putFail("微信获取信息出错");
        }
        return JsonResult.putSuccess(user);
    }
}
